package com.yundou.www.wrpc.core.net;

import com.alibaba.fastjson.JSON;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author wangweiwei
 * @since 2021/7/22
 */
public class ServiceProxy {

    private static Map<String ,Object> serviceInstanceMap = new HashMap<>(16);


    private static Map<String , Method> serviceInstanceMethodMap = new HashMap<>(16);



    public static void putServiceInstance(String name , Object instance) {
        if (Objects.nonNull(instance)) {
            serviceInstanceMap.put(name ,instance);
        }

    }


    public static void putServiceInstanceMethod(String name , Method method) {
        if (Objects.nonNull(method)) {
            serviceInstanceMethodMap.put(name ,method);
        }

    }



    public static WRpcResponse doExecuteRequest(WRpcRequest request) {
        //获取服务实例
        Object serviceInstance = serviceInstanceMap.get(request.getInterfaceName());

        Method method = serviceInstanceMethodMap.get(request.getInterfaceName() + "." + request.getMethodName());

        WRpcResponse response = new WRpcResponse();
        try {
            Object[] params = request.getParams();
            Object[] objects = new Object[params.length];
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (objects.length > 0 && parameterTypes.length > 0) {

                for (int i = 0; i < objects.length  ;i ++) {

                    objects[i] = JSON.parseObject(JSON.toJSONString(params[i]), parameterTypes[i]);
                }

            }

            Object invoke = method.invoke(serviceInstance, objects);
            response.setCode(0);
            response.setResult(invoke);
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(1);
        }
        return response;

    }

}
